<?php
namespace app\common\controller;

use app\common\controller\BaseController;
use think\facade\Config;

/**
 * zjutsxj@qq.com
 * 后台管理根控制器
 */
class AdminBaseController extends BaseController
{

    protected function initialize()
    {
        if (!cookie('?admin_manage')) {
            $this->redirect(url('/login'));
        }
        // 后台配置
        $this->assign('setting', config('setting.'));

        $siteid = $this->request->param('siteid', 0); // 站点id
        $columnid = $this->request->param('columnid', 0); // 栏目id
        $this->assign('siteid', $siteid);
        $this->assign('columnid', $columnid);
        $this->assign('urlparam', 'siteid=' . $siteid . '&columnid=' . $columnid);

        $controller = strtolower($this->request->controller()); // 当前控制器
        $action = strtolower($this->request->action()); // 当前操作方法

        // 顶部选中
        $active = '';

        // 内容左侧导航
        $sidebar_list = ''; // 侧边栏内容

        // 系统栏目
        $sys_controller = array('setting', 'manage', 'databk', 'theme', 'site', 'module', 'plugin');
        if (in_array($controller, $sys_controller)) {
            // 系统
            $sidebar_list = self::sidebarSys($controller, $action);
            $active = 'setting';
        } elseif ($siteid > 0) {
            // 站点
            $sidebar_list = self::sidebarList($siteid, $columnid);
        } else {
            // 首页
            $sidebar_list = self::sidebarHome($controller);
            $active = 'home';
        }

        // 顶部左侧导航
        $dropdown_left = self::dropdownLeft($siteid, $active);
        // 顶部右侧导航
        $dropdown_right = self::dropdownRight($active);

        $this->assign('dropdown_left', $dropdown_left);
        $this->assign('dropdown_right', $dropdown_right);
        $this->assign('sidebar_list', $sidebar_list);
    }

    /**
     * 首页列表
     * @return [type] [description]
     */
    private function gethomelist()
    {
        $list = array();
        $list[] = ['title' => '系统信息', 'icon' => 'info-sign', 'controller' => 'index', 'url' => url('/')];
        $list[] = ['title' => '修改资料', 'icon' => 'edit', 'controller' => '', 'url' => url('/manage/info')];
        $list[] = ['title' => '修改密码', 'icon' => 'key', 'controller' => '', 'url' => url('/manage/pwd')];
        $list[] = ['title' => '退出系统', 'icon' => 'signout', 'controller' => '', 'url' => url('/index/logout')];
        return $list;
    }

    /**
     * 系统栏目
     * @return [type] [description]
     */
    private function getsyslist()
    {
        $list = array();
        // https://www.kancloud.cn/zjutsxj/yimaoadmin
        if (check_auth('setting-index')) {
            $list[] = ['title' => '系统设置', 'icon' => 'cog', 'controller' => 'setting', 'action' => 'index', 'url' => url('/setting')];
        }
        if (check_auth('manage-index')) {
            $list[] = ['title' => '管理列表', 'icon' => 'user', 'controller' => 'manage', 'action' => 'index,groups', 'url' => url('/manage')];
        }
        if (check_auth('databk-index')) {
            $list[] = ['title' => '数据备份', 'icon' => 'database', 'controller' => 'databk', 'action' => 'index', 'url' => url('/databk')];
        }
        if (check_auth('theme-index')) {
            $list[] = ['title' => '主题管理', 'icon' => 'layout', 'controller' => 'theme', 'action' => 'index', 'url' => url('/theme')];
        }
        if (check_auth('site-index')) {
            $list[] = ['title' => '站点管理', 'icon' => 'sitemap', 'controller' => 'site', 'action' => 'index,column,column_sort,param', 'url' => url('/site')];
        }
        if (check_auth('module-index')) {
            $list[] = ['title' => '模块管理', 'icon' => 'cube-alt', 'controller' => 'module', 'action' => 'index', 'url' => url('/module')];
        }
        if (check_auth('plugin-index')) {
            $list[] = ['title' => '插件管理', 'icon' => 'lightbulb', 'controller' => 'plugin', 'action' => 'index', 'url' => url('/plugin')];
        }
        $list[] = ['title' => '修改资料', 'icon' => 'edit', 'controller' => 'manage', 'action' => 'info', 'url' => url('/manage/info')];
        $list[] = ['title' => '修改密码', 'icon' => 'key', 'controller' => 'manage', 'action' => 'pwd', 'url' => url('/manage/pwd')];
        $list[] = ['title' => '退出系统', 'icon' => 'signout', 'controller' => 'manage', 'action' => 'logout', 'url' => url('/index/logout')];
        return $list;
    }

    /**
     * 导航条 左侧下拉
     * @return [type] [description]
     */
    private function dropdownLeft($siteid = 0, $dropdown_active = '')
    {
        $sites = self::getSites();
        $html = '';
        foreach ($sites as $key => $site) {
            $menu = '';
            // 站点选中 只在站点管理栏目中有效
            $active = '';
            if ($dropdown_active == '') {
                $active = $site['site_id'] != $siteid ?: 'active';
            }

            $name = sprintf(
                '<a data-toggle="dropdown">%s <span class="caret"></span> </a>',
                $site['site_name']
            );

            if (check_auth($site['site_id'] . '-0')) {
                $menu = sprintf(
                    '<li><a href="%s"><i class="icon icon-desktop"></i> 网站设置</a></li>',
                    url('/website', 'siteid=' . $site['site_id'])
                );
            }

            // 获取栏目列表 关联 module 模块功能
            $list = self::getColumns($site['site_id']);
            if ($list) {
                // 列表转树结构
                $tree = list_to_tree($list, 'column_id', 'column_pid', '_child');
                $menu .= self::createDropDownMenu($tree);
            }

            // 没有内容直接隐藏该栏目
            if ($menu == '') {
                continue;
            }

            $tpl = '<li class="dropdown %s">%s <ul class="dropdown-menu">%s</ul></li>';
            $html .= sprintf($tpl, $active, $name, $menu);
        }
        return $html;
    }

    /**
     * 导航条 右侧下拉
     * @return [type] [description]
     */
    private function dropdownRight($dropdown_active = '')
    {
        $active = $dropdown_active != 'setting' ? '' : 'active';
        // 系统栏目
        $list = self::getsyslist();

        // 生成 html 源代码
        $html = '<li class="dropdown %s">';
        $html .= '  <a class="dropdown-toggle" data-toggle="dropdown" title="系统设置">';
        $html .= '      <i class="icon icon-cogs f16"></i>';
        $html .= '  </a>';
        $html .= '  <ul class="dropdown-menu" role="menu">%s</ul>';
        $html .= '</li>';
        // 生成下拉菜单
        $menu = '';
        $str = '<li><a href="%s"><i class="icon icon-%s"></i> %s</a></li>';
        foreach ($list as $key => $value) {
            $menu .= sprintf($str, $value['url'], $value['icon'], $value['title']);
        }
        $html = sprintf($html, $active, $menu);
        return $html;
    }

    /**
     * 内容页 首页列表
     * @return [type] [description]
     */
    private function sidebarHome($controller = '')
    {
        // 系统栏目
        $list = self::gethomelist();
        $active = '';
        // 生成 html 源代码
        $html = '<h2>系统信息</h2>';
        $str = '<li class="%s"><a href="%s"><i class="icon icon-%s"></i> %s</a></li>';
        foreach ($list as $key => $value) {
            $active = $controller == $value['controller'] ? 'active' : '';
            $html .= sprintf($str, $active, $value['url'], $value['icon'], $value['title']);
        }
        return $html;
    }

    /**
     * 内容页 系统列表
     * @return [type] [description]
     */
    private function sidebarSys($controller = '', $action = '')
    {
        // 系统栏目
        $list = self::getsyslist();

        // 生成 html 源代码
        $html = '<h2>系统管理</h2>';
        $str = '<li class="%s"><a href="%s"><i class="icon icon-%s"></i> %s</a></li>';
        foreach ($list as $key => $value) {
            // 左侧栏目选中
            $active = '';
            if ($controller != '' && $controller == $value['controller']) {
                if (strpos($value['action'], $action) !== false) {
                    $active = 'active';
                }
            }
            $html .= sprintf($str, $active, $value['url'], $value['icon'], $value['title']);
        }
        return $html;
    }

    /**
     * 内容页 左侧列表
     */
    private function sidebarList($siteid = 0, $columnid = 0)
    {
        $site = self::getSite($siteid);
        $html = '';
        if ($site) {
            $html .= sprintf('<h2>%s</h2>', $site['site_name']);
            if (check_auth($siteid . '-0')) {
                $active = $columnid != 0 ?: 'active';
                $html .= sprintf(
                    '<li class="%s"><a href="%s"><i class="icon icon-desktop"></i> 网站设置</a></li>',
                    $active, url('/website', 'siteid=' . $site['site_id'])
                );
            }
            // 获取栏目列表 关联 module 模块功能
            $list = self::getColumns($siteid);
            if ($list) {
                // 列表转树结构
                $tree = list_to_tree($list, 'column_id', 'column_pid', '_child');
                $path = '0';
                if ($columnid > 0) {
                    $column = self::getColumn($columnid);
                    $path = '0,' . $column['column_path'] . ',' . $columnid;
                }
                $html .= self::createMenu($tree, $path);
            }
        }
        return $html;
    }

    /**
     * [createMenu 生成menu html 适合zui的导航菜单的html]
     */
    protected function createMenu($tree, $path = '0', $level = 0)
    {
        $html = '';
        $level++;
        $mypath = $path . ',';

        foreach ($tree as $item) {
            $siteid = $item['column_siteid'];
            $columnid = $item['column_id'];
            $name = $item['column_name'];
            $icon = $item['column_icon'];
            $child = isset($item['_child']) ? $item['_child'] : false;
            //$module = isset($item['module']) ? $item['module'] : false;
            $module = isset($item['module_path']) ? $item['module_path'] : '';

            //判断权限
            if (!check_auth($siteid . '-' . $columnid)) {
                continue;
            }

            // 栏目选中
            $active = '';
            if ($child) {
                $active = strpos($mypath, ',' . $columnid . ',') !== false ? 'open' : '';
            } else {
                $active = strpos($mypath, ',' . $columnid . ',') !== false ? 'active' : '';
            }

            // 链接
            $url = '#';
            if ($module != '' && $module != null) {
                $url = url('/' . $module, 'siteid=' . $siteid . '&columnid=' . $columnid);
            }

            // 显示子栏目
            $sub = '';
            if ($child and $level < 3) {
                $sub = '<ul>' . self::createMenu($child, $path, $level) . '</ul>';
            }
            $tpl = '<li class="%s"><a href="%s"><i class="icon %s"></i> %s</a> %s</li>';
            $html .= sprintf($tpl, $active, $url, $icon, $name, $sub);
        }
        return $html;
    }

    /**
     * [createDropDownMenu 生成menu html 适合zui的导航菜单的html]
     */
    protected function createDropDownMenu($tree)
    {
        $html = '';
        foreach ($tree as $item) {
            $active = '';
            $siteid = $item['column_siteid'];
            $columnid = $item['column_id'];
            $name = $item['column_name'];
            $icon = $item['column_icon'];
            $child = isset($item['_child']) ? $item['_child'] : false;
            $module = isset($item['module_path']) ? $item['module_path'] : '';
            //判断权限
            if (!check_auth($siteid . '-' . $columnid)) {
                continue;
            }

            // 链接
            $url = '';
            if ($module != '' && $module != null) {
                $url = sprintf('href="%s"', url('/' . $module, 'siteid=' . $siteid . '&columnid=' . $columnid));
            }

            // 显示子栏目
            $sub = '';
            if ($child) {
                $active = 'dropdown-submenu';
                $sub = '<ul class="dropdown-menu">' . self::createDropDownMenu($child) . '</ul>';
            }
            $tpl = '<li class="%1$s"><a %2$s><i class="icon %3$s"></i> %4$s</a> %5$s</li>';
            $html .= sprintf($tpl, $active, $url, $icon, $name, $sub);
        }
        return $html;
    }
}
